#!/bin/bash

# UmaInsight 测试运行脚本
# 使用 Python 虚拟环境和前端测试

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🚀 UmaInsight 测试运行脚本${NC}"
echo "======================================"

# 检查并激活 Python 虚拟环境
if [ ! -d "backend/.venv" ]; then
    echo -e "${YELLOW}📦 创建 Python 虚拟环境...${NC}"
    python3 -m venv backend/.venv
    source backend/.venv/bin/activate
    pip install --upgrade pip
    pip install -r backend/requirements.txt
else
    echo -e "${GREEN}✅ 激活 Python 虚拟环境...${NC}"
    source backend/.venv/bin/activate
fi

echo ""
echo -e "${BLUE}📊 开始执行测试...${NC}"
echo "======================================"

# 设置测试环境变量
export PYTHONPATH="${PYTHONPATH}:$(pwd):$(pwd)/backend"
export SECRET_KEY="test-secret-key-for-testing-only"
export ENVIRONMENT="testing"
export DEBUG="true"

# 执行后端测试 - 按分类目录执行
echo -e "${YELLOW}🐍 执行后端 Python 测试...${NC}"
echo "--------------------------------------"

# 确保使用虚拟环境的python
PYTHON_CMD="backend/.venv/bin/python"

# 单元测试
echo -e "${BLUE}📝 单元测试:${NC}"
$PYTHON_CMD -m pytest backend/tests/unit/ -v --tb=no | grep -E "(PASSED|FAILED|ERROR|test_)" || true

echo ""

# 集成测试
echo -e "${BLUE}🔗 集成测试:${NC}"
$PYTHON_CMD -m pytest backend/tests/integration/ -v --tb=no | grep -E "(PASSED|FAILED|ERROR|test_)" || true

echo ""

# API测试
echo -e "${BLUE}🌐 API 测试:${NC}"
$PYTHON_CMD -m pytest backend/tests/api/ -v --tb=no | grep -E "(PASSED|FAILED|ERROR|test_)" || true

# 统计后端测试结果
BACKEND_TESTS=$($PYTHON_CMD -m pytest backend/tests/ -q --tb=no 2>/dev/null | grep -E "(passed|failed)" | awk '{sum+=$2} END {print sum+0}' || echo "0")
BACKEND_PASSED=$($PYTHON_CMD -m pytest backend/tests/ -q --tb=no 2>/dev/null | grep -E "(passed)" | awk '{sum+=$2} END {print sum+0}' || echo "0")

echo ""
echo -e "${GREEN}✅ 后端测试完成: ${BACKEND_PASSED}/${BACKEND_TESTS} 通过${NC}"
echo ""

# 执行前端测试
echo -e "${YELLOW}⚛️ 执行前端 React/TypeScript 测试...${NC}"
echo "--------------------------------------"

cd frontend

# 安装依赖（如果需要）
if [ ! -d "node_modules/axios-mock-adapter" ]; then
    echo -e "${BLUE}📦 安装前端测试依赖...${NC}"
    npm install axios-mock-adapter @types/axios-mock-adapter --save-dev --legacy-peer-deps
fi

# 运行前端测试 - 按分类目录执行
echo -e "${BLUE}🎯 前端测试执行:${NC}"

# 单元测试
echo -e "${YELLOW}  📝 单元测试:${NC}"
npm test -- --watchAll=false --testPathPattern="__tests__/unit/" --passWithNoTests 2>/dev/null | grep -E "(PASS|FAIL|Test Suites|Tests:)" || true

# 集成测试
echo -e "${YELLOW}  🔗 集成测试:${NC}"
npm test -- --watchAll=false --testPathPattern="__tests__/integration/" --passWithNoTests 2>/dev/null | grep -E "(PASS|FAIL|Test Suites|Tests:)" || true

# 端到端测试
echo -e "${YELLOW}  🌐 端到端测试:${NC}"
npm test -- --watchAll=false --testPathPattern="__tests__/e2e/" --passWithNoTests 2>/dev/null | grep -E "(PASS|FAIL|Test Suites|Tests:)" || true

# API测试
echo -e "${YELLOW}  🌐 API测试:${NC}"
npm test -- --watchAll=false --testPathPattern="__tests__/api/" --passWithNoTests 2>/dev/null | grep -E "(PASS|FAIL|Test Suites|Tests:)" || true

# 组件测试
echo -e "${YELLOW}  🧩 组件测试:${NC}"
npm test -- --watchAll=false --testPathPattern="__tests__/components/" --passWithNoTests 2>/dev/null | grep -E "(PASS|FAIL|Test Suites|Tests:)" || true

# Hook测试
echo -e "${YELLOW}  🪝 Hook测试:${NC}"
npm test -- --watchAll=false --testPathPattern="__tests__/hooks/" --passWithNoTests 2>/dev/null | grep -E "(PASS|FAIL|Test Suites|Tests:)" || true

# 工具函数测试
echo -e "${YELLOW}  🛠️ 工具函数测试:${NC}"
npm test -- --watchAll=false --testPathPattern="__tests__/utils/" --passWithNoTests 2>/dev/null | grep -E "(PASS|FAIL|Test Suites|Tests:)" || true

# 统计前端测试结果 - 简化统计方式
FRONTEND_TOTAL=0
FRONTEND_PASSED=0

# 分别统计各类型测试数量
for test_type in "unit" "integration" "e2e" "api" "components" "hooks" "utils"; do
    echo -e "${YELLOW}  📊 统计 ${test_type} 测试:${NC}"
    TEST_OUTPUT=$(npm test -- --watchAll=false --testPathPattern="__tests__/${test_type}/" --passWithNoTests --json 2>/dev/null || echo '{"numTotalTests":0,"numPassedTests":0}')
    TYPE_TOTAL=$(echo "$TEST_OUTPUT" | grep -o '"numTotalTests":[0-9]*' | cut -d':' -f2 | head -1 || echo "0")
    TYPE_PASSED=$(echo "$TEST_OUTPUT" | grep -o '"numPassedTests":[0-9]*' | cut -d':' -f2 | head -1 || echo "0")
    FRONTEND_TOTAL=$((FRONTEND_TOTAL + TYPE_TOTAL))
    FRONTEND_PASSED=$((FRONTEND_PASSED + TYPE_PASSED))
done

cd ..

echo ""
echo -e "${GREEN}✅ 前端测试完成: ${FRONTEND_PASSED}/${FRONTEND_TOTAL} 通过${NC}"
echo ""

# 总体统计
TOTAL_TESTS=$((BACKEND_TESTS + FRONTEND_TOTAL))
TOTAL_PASSED=$((BACKEND_PASSED + FRONTEND_PASSED))

# 防止除零错误
if [ $TOTAL_TESTS -eq 0 ]; then
    PASS_RATE=0
else
    PASS_RATE=$((TOTAL_PASSED * 100 / TOTAL_TESTS))
fi

echo "======================================"
echo -e "${BLUE}📈 测试执行总结${NC}"
echo "======================================"
echo -e "🔧 后端测试: ${GREEN}${BACKEND_PASSED}/${BACKEND_TESTS} 通过${NC}"
echo -e "⚛️ 前端测试: ${GREEN}${FRONTEND_PASSED}/${FRONTEND_TOTAL} 通过${NC}"
echo -e "🎯 总体测试: ${GREEN}${TOTAL_PASSED}/${TOTAL_TESTS} 通过${NC}"
echo -e "📊 通过率: ${GREEN}${PASS_RATE}%${NC}"

if [ $TOTAL_PASSED -eq $TOTAL_TESTS ]; then
    echo -e "${GREEN}🎉 所有测试通过！系统稳定可靠。${NC}"
    exit 0
else
    echo -e "${RED}❌ 存在测试失败，请检查上述输出。${NC}"
    exit 1
fi